import pymysql


class Dbmysql():
    
    # 构造方法来初始化，数据库信息
    def __init__(self,host="xxx",port='xxx',user="xxx",password='xxx',db="xxx",charset='utf8'):
        self.host = host
        self.user = user
        self.password = password
        self.db = db
        self.port = port
        self.charset = charset
    
    # 查询方法
    def query(self,sql):
        try:
            db = pymysql.connect(host=self.host,port=self.port,user=self.user,password=self.password,db=self.db)
            cursor = db.cursor()  # 获取游标
            cursor.execute(sql) # 执行查询sql语句
            res = cursor.fetchall()  # 获取查询结果
            db.close() # 关闭数据库连接
            return res
        except Exception as s:
            print(s)
            return False
            
        
    
    def commet(self,sql):
        '''
            名字:新增/删除/修改方法
            参数:sql:查询sql语句
            返回值:操作成功返回True         操作失败:返回false
        '''
        try:
            db = pymysql.connect(host=self.host,user=self.user,password=self.password,db=self.db) # 连接并且得到数据库的操作对象
            cursor = db.cursor() # 获取游标
            cursor.execute(sql) # 执行sql
            db.commit() # 提交修改
            db.close() # 关闭数据库
            return  True
        except Exception as s:  # 打印出错的日志 
            print(s)
            return  False


    def get_id(self,sql_res):
        '''
        清洗查询数据库查询结果中的id值
        :param sql_res:
        :return:
        '''
        sql_id_list = []
        for num in sql_res:
            sql_id_list.append(str(num[0]))
        return sql_id_list

    def get_data(self,r,parameter,args):

        '''
        :param r: 构造请求返回的结果
        :param parameter: 需要参数的key值
        :param args: 字典中取出的值
        :return: 取出response中的某个值
        '''
        ms_course_list = []
        for ms_course in r.json()['data'][parameter]:
            ms_course_list.append(ms_course[args])
        return ms_course_list